package com.example.learn_mybatis.filter;

import com.example.learn_mybatis.cache.AuthCache;
import com.example.learn_mybatis.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@Slf4j
@WebFilter("/*")
public class AuthFilter implements Filter {

    @Autowired
    private AuthCache authCache;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 获取所有用户的权限 缓存起来
        authCache.getAllUsersAuth();
        log.info("过滤器启动.....");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String token = req.getHeader("Authorization");

        String uri = req.getRequestURI();
        String method = req.getMethod();

        log.info("uri: {}, method: {}", uri, method);

        if(uri.contains("login")){
            filterChain.doFilter(servletRequest, servletResponse);

            // 返回结束这个请求
            return;
        }

        if(uri.contains("/refreshAuth")){
            authCache.getAllUsersAuth();
            resp.setStatus(200);
            log.info("刷新权限信息");
            return;
        }

        if(token==null){
            resp.setStatus(401);
            log.info("未登录");
            return;
        }

        try{
            Claims claims = JwtUtil.getClaimsFromToken(token);
            String id = claims.get("id").toString();
            boolean hasAuth = authCache.hasAuth(Integer.valueOf(id), uri, method);
            log.info("hasAuth: {}", hasAuth);

            if(!hasAuth){
                resp.setStatus(403);
                log.info("没有该权限");
                return;
            }

        } catch (Exception e) {
            resp.setStatus(401);
            return;
//            throw new RuntimeException(e);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
